/*
 * @Date: 2024-07-08 11:28:50
 * @LastEditors: lyx
 * @LastEditTime: 2024-07-08 13:24:50
 * @FilePath: \minute-dota2\app\i18n\index.ts
 * @Description: 服务端组件使用 i18n
 */

import { createInstance } from 'i18next'
import resourcesToBackend from 'i18next-resources-to-backend'
import { initReactI18next } from 'react-i18next/initReactI18next'
import siteMetadata from '@/data/siteMetadata'

const { fallbackLanguage, languages } = siteMetadata

const initI18next = async (lng = fallbackLanguage, ns = 'basic') => {
  const i18nInstance = createInstance()
  await i18nInstance
    .use(initReactI18next)
    .use(resourcesToBackend((language, namespace) => import(`./locales/${language}/${namespace}.json`)))
    .init({
      // debug: true,
      supportedLngs: languages,
      fallbackLng: fallbackLanguage,
      lng,
      fallbackNS: 'basic',
      defaultNS: 'basic',
      ns
    })
  return i18nInstance
}

export async function useTranslation(lng, ns = '', options = {}) {
  const i18nextInstance = await initI18next(lng, ns)
  return {
    t: i18nextInstance.getFixedT(lng, Array.isArray(ns) ? ns[0] : ns, options.keyPrefix),
    i18n: i18nextInstance
  }
}
